<?php
if(!defined('DOKU_INC')) define('DOKU_INC',realpath(dirname(__FILE__).'/../../').'/');
if(!defined('DOKU_PLUGIN')) define('DOKU_PLUGIN',DOKU_INC.'lib/plugins/');
require_once(DOKU_PLUGIN.'syntax.php');

class syntax_plugin_bbcodeextensions_anchor extends DokuWiki_Syntax_Plugin {

    function getType() { return 'disabled'; }
    function getPType() { return 'normal'; }
    function getAllowedTypes() { return array('disabled'); }   
    function getSort() { return 110; }
    function connectTo($mode){
        $this->Lexer->addSpecialPattern('\[a\][0-9a-zA-Z_\-:]+?\[/a\]', $mode, 'plugin_bbcodeextensions_anchor');
    }

    function handle($match, $state, $pos, Doku_Handler $handler) {
        switch ($state) {
          case DOKU_LEXER_ENTER :
            return array($state, $match);

          case DOKU_LEXER_UNMATCHED :
            return array($state, $match);

          case DOKU_LEXER_EXIT :
            return array($state, '');
           
           case DOKU_LEXER_SPECIAL :
			return array($state, $match);

        }
        return array();
    }

	function render($mode, Doku_Renderer $renderer, $data) {
		list ($state, $match) = $data;
		switch ($state) {
			case DOKU_LEXER_ENTER :      
			break;

			//case DOKU_LEXER_UNMATCHED :
			case DOKU_LEXER_SPECIAL :
			if(in_array($mode, ['xhtml', 's5'], true)) {
				$match= substr($match, 3, -4);
				$match= $renderer->_xmlEntities($match); // htmlspecialchars($match);
				$renderer->doc .= '<a id="'. $match. '" name="'. $match. '"></a>';
			} else
			if ($mode==='text') {
				$renderer->doc .= $this->getConf('anchor_symbol');
				$renderer->doc .= '['. $match. ']';
			} else {
				$renderer->doc .= '#['. $match. '] ';
			}
			
			break;
			
			case DOKU_LEXER_EXIT:
			break;

		}
        return false;
    }
}
